<template>
  <div class="auth-container">
    <el-card class="auth-card">
      <div class="tab-buttons">
        <el-button
          :type="activeTab === 'login' ? 'primary' : 'default'"
          @click="activeTab = 'login'"
        >
          登录
        </el-button>
        <el-button
          :type="activeTab === 'register' ? 'primary' : 'default'"
          @click="activeTab = 'register'"
        >
          注册
        </el-button>
      </div>

      <!-- 登录表单 -->
      <el-form
        v-if="activeTab === 'login'"
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        label-position="top"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="full-button" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
        label-position="top"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" class="full-button" @click="handleRegister">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

import { useUserStore } from '@/stores/userStore.js'
import { login, register } from '@/api/auth.js'
import router from '@/router/index.js'

const activeTab = ref('login')

// 登录逻辑
const loginForm = reactive({
  username: '',
  password: '',
})

const userStore = useUserStore()

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const loginFormRef = ref()

const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      login({
        username: loginForm.username,
        password: loginForm.password,
      }).then((response) => {
        if (response.data.token) {
          localStorage.setItem('token', response.data.token)
          const { username, email, avatar, roles } = response.data
          userStore.setUser({
            username,
            email,
            avatar,
            roles,
          })
          ElMessage.success('登录成功')
          // 跳转到首页或其他页面
          router.push('/')
        } else {
          ElMessage.error('登录失败，请重试')
        }
      })
    } else {
      ElMessage.error('请输入正确的用户名和密码')
    }
  })
}

// 注册逻辑
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
})

const registerRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

const registerFormRef = ref()

const handleRegister = () => {
  registerFormRef.value.validate((valid) => {
    if (valid) {
      register({
        username: registerForm.username,
        email: registerForm.email,
        password: registerForm.password,
      })
        .then((response) => {
          if (response.data.code === 1) {
            ElMessage.success('注册成功')
            activeTab.value = 'login'
          } else {
            ElMessage.error('注册失败：' + response.data.message)
          }
        })
        .catch((error) => {
          ElMessage.error('注册失败：' + error.message)
        })
    } else {
      ElMessage.error('请输入完整表单')
    }
  })
}
</script>

<style scoped>
.auth-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to right, #83a4d4, #b6fbff);
}

.auth-card {
  width: 400px;
  padding: 25px;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.tab-buttons {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.full-button {
  width: 100%;
}
</style>
